import java.util.Hashtable;
import java.util.concurrent.locks.Lock;

public class LookupProvider implements rmibroker {
	
	private static Hashtable<String, Hashtable<String, String>> db;
	private static Lock dbLock;
	
	public LookupProvider(Lock dbLock, Hashtable<String, Hashtable<String, String>> db){
		LookupProvider.db = db;
		LookupProvider.dbLock = dbLock;
	}
	
	public String query(String id, String name, String value) {

		String reply = "FALSE";

		//Ensure the format of arguments is correct
		if (!validateInput(id, name, value)) {
			return msg.E3;
		}

		//retrieve the triple set
		dbLock.lock();
		Hashtable<String, String> content = db.get(name);
		dbLock.unlock();
		
		String tempResult = "";

		//Handle case where multiple results are returned
		if (content != null && value.equals("*")) {
			//Copy results into result set
			double version = 0.0;
			double tempVersion = 0.0;
			int VERSION = 2;
			for (String k : content.keySet()) {
				
				tempResult = content.get(k);
				
				String[] service = tempResult.split(" ");
				
				tempVersion = Double.parseDouble(service[VERSION]);
				
				if(tempVersion > version)
					reply = tempResult;
				
			}
		} 

		return reply;
	}
	private boolean validateInput(String id, String name, String value) {

		if (id == null || name == null || value == null || id.length() > 32
				|| name.length() > 32 || value.length() > 32
				|| id.length() == 0 || name.length() == 0
				|| value.length() == 0) {
			return false;
		}

		return true;

	}
}
